package com.rzl.expense.common.utils.sign;


import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * 单点登录用到的aes工具类
 *
 * @author admin
 * @date 2023/09/18
 */
public class SooAesUtils {
    /**
     * 密钥
     */
    final static String KEY = "1ncms*2eoms*3ms4";
    /**
     * 费用关键字
     */
    final static String EXPENSE_KEY = "t2Ap1Q12BC9Ad7fI";

    static Cipher GetCipher(int mode, String sKey) throws Exception {

        /*
          加密密钥长度为16位
         */
        if ((sKey == null) || (sKey.length() != 16)) {
            return null;
        }
        byte[] raw = sKey.getBytes("utf-8");
        SecretKeySpec sKeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(mode, sKeySpec);
        return cipher;

    }

    /**
     * 对信息进行AES-128-ECB加密
     *
     * @param sSrc 加密原始信息
     * @param sKey 加密密钥
     * @return 加密后信息
     * @throws Exception
     */
    public static String Encrypt(String sSrc, String sKey) throws Exception {

        Cipher cipher = GetCipher(Cipher.ENCRYPT_MODE, sKey);
        if (cipher == null) {
            return "";
        }
        byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
        return new Base64().encodeToString(encrypted);
    }

    /**
     * 对信息进行AES-128-ECB解密获得原始信息
     *
     * @param sSrc 加密后信息
     * @param sKey 加密密钥
     * @return 原始信息
     * @throws Exception
     */
    public static String Decrypt(String sSrc, String sKey) throws Exception {

        Cipher cipher = GetCipher(Cipher.DECRYPT_MODE, sKey);
        if (cipher == null) {
            return "";
        }
        byte[] encryptedBase64 = new Base64().decode(sSrc);
        byte[] original = cipher.doFinal(encryptedBase64);
        String originalString = new String(original, "utf-8");
        return originalString;
    }

    /**
     * 对信息进行AES-128-ECB解密获得原始信息
     *
     * @param sSrc 加密后信息
     * @return 原始信息
     * @throws Exception
     */
    public static String Decrypt(String sSrc) throws Exception {

        Cipher cipher = GetCipher(Cipher.DECRYPT_MODE, KEY);
        if (cipher == null) {
            return "";
        }
        byte[] encryptedBase64 = new Base64().decode(sSrc);
        byte[] original = cipher.doFinal(encryptedBase64);
        String originalString = new String(original, "utf-8");
        return originalString;
    }

    public static void main(String[] args) throws Exception {
      /*  String sSrc = "zhaozhong@gx.cmcc";
        String encrypt = Encrypt(sSrc, KEY);
        //lyM04Ym9VB46FUH01dJEQhMitBWB/YKfBw/ldlp5t4g=
        System.out.println(encrypt);*/
        // String encrypt = "zyfr/fwKWSFyB+jTTbBmRRLbPbDyj8awkI0Mbgkj4JA="; //NCMS|xingzhe@hq.cmcc
        String encrypt = "dPfgtUEoCCUbAHv17bZqEuyEgRaF3iZ68AzFq+ToT8w=";
        String decrypt = Decrypt(encrypt, KEY);
        System.out.println(decrypt);
    }
}
